﻿using Kevin.Comm.Logger;
using Kevin.Comm.Utility;
using RiderShop.Mobile.Modle.Customer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace RiderShop.WebSite.Controllers.Customer
{
    public class OAuthController : Controller
    {
        public ActionResult Login(int type)
        {
            var url = OAuthModel.CreateConnectFactory(type);

            return Redirect(url);
        }


        public ActionResult Verify()
        {

            Tracer.TraceLog("1-OAutoCallbackURL:" + Request.Url.ToString(), "OAutoCallbackURL", "OAutoCallbackURL", true);
            String orgstate = Request.QueryString["state"];
            orgstate = !string.IsNullOrEmpty(orgstate) ? Uri.UnescapeDataString(orgstate) : orgstate;
            String code = Request.QueryString["code"];
            code = !string.IsNullOrEmpty(code) ? Uri.UnescapeDataString(code) : code;

            string siteTypeStr = !string.IsNullOrEmpty(orgstate) && orgstate.Split(',').Length == 2 ? orgstate.Split(',')[1] : string.Empty;
            string state = !string.IsNullOrEmpty(siteTypeStr) ? orgstate.Split(',')[0] : string.Empty;

            if (!String.IsNullOrEmpty(state))
            {
                #region 处理站点

                int site = 1;
                int.TryParse(siteTypeStr, out site);
                #endregion
                //object guid = KevinCache.Get("ConnectGuid");
                //if (guid != null)
                {
                    //if (guid.ToString().CompareTo(state) == 0)//不对比本站生成guid，可能会丢失
                    {
                        KevinCache.Remove("ConnectGuid");
                        //if (Regex.IsMatch(code, regexCode))//不对比本站生成guid，可能会丢失
                        {
                            OAuthModel model = new OAuthModel();
                            try
                            {
                                var result = model.Verify(site, code);
                                if (result)
                                {
                                    return Redirect("/MyAccount/Profile");
                                }
                                else
                                {
                                    return Redirect("/Customer/Login");
                                }
                            }
                            catch (Exception ex)
                            {
                                Tracer.TraceLog("1-OAutoCallbackURL:验证第三方异常" + ex.Message, "OAutoCallbackURL", "OAutoCallbackURL", true);

                                return Redirect("/Customer/Login");
                            }
                        }
                    }
                }

            }


            return Redirect("/Customer/Login");
        }
    }
}
